<template>
	<div class="source_material">
		<!-- 新建文件夹 -->
		<NewFolder :visible="folderVisible" :groupData="currentLibrary" :merchantCanView="currentMaterial.id === 2"
			@onCancel="folderVisible = false" @onSubmit="closeFolder" />
		<!-- 上传文件 -->
		<UploadFileModal :visible="materialVisible" :type="currentFolder.folder_type" :fileData="currentFolder"
			@onCancel="materialVisible = false" @onSubmit="closeMaterial" />
		<div class="new_folder" v-if="
			!showMaterial && (currentMaterial.id == 1 || currentMaterial.id == 2)
		">
			<a-button @click="addFolder" class="folder_btn" type="text" size="small">
				<template #icon>
					<FolderAddOutlined />
				</template>
				新建文件夹
			</a-button>
		</div>

		<div class="new_material" v-if="
			showMaterial && (currentMaterial.id == 1 || currentMaterial.id == 2)
		">
			<a-button @click="addMaterial" class="folder_btn" type="text" size="small">
				<template #icon>
					<FolderAddOutlined />
				</template>
				添加素材
			</a-button>
			<a-button v-if="currentFolder.folder_type == 'audio' || currentMaterial.id == 4" @click="textToAudio"
				class="folder_btn" type="text" size="small">
				文字转语音
			</a-button>
			<a-button @click="backToFolder" class="folder_btn" type="text" size="small">
				<template #icon>
					<LeftOutlined />
				</template>
				返回
			</a-button>
		</div>

		<div class="title_con" v-if="
			showMaterial && (currentMaterial.id == 1 || currentMaterial.id == 2)
		  ">
			<a style="color: #2878FF;" @click="backToFolder">{{ currentMaterial.name }}</a>
			<span style="margin: 0 10px">/</span>{{ currentFolder.folder_name }}
		</div>

		<div class="main_con" id="mainCon" v-if="!showMaterial || currentMaterial.id == 3 || currentMaterial.id == 4">
			<component @expandTab="expandTab" @folderType="handleTypeChange" @getCurrentLibrary="getCurrentLibrary"
				@chooseMaterial="screenMaterial" :tagList="tagList" :is="currentMaterial.type" />
		</div>

		<div class="folder_con" v-if="!showMaterial">
			<folderList :isLoading="folderLoading" :list="folderData" @choose="chooseFolder" />
		</div>

		<div ref="resultRef" :style="{
			maxHeight: showBottomCount
			  ? `calc(100% - ${mainConHeight + 70}px)`
			  : `calc(100% - ${mainConHeight}px)`,
			}" class="material_con" v-if="showMaterial">
			<materialList :checkType="checkType" @showBottom="showBottom" :isLoading="materialLoading"
				:list="materialData" :currentMaterial="currentMaterial" :currentTagId="currentTagId"
				@refrashMaterial="refrashMaterial" @choose="chooseMaterial" :showCount="showBottomCount" />
		</div>
		<div class="material_bottom" v-if="showBottomCount && currentFolder.folder_type != 'text'">
			<a-button size="small" class="bottom_btn" @click="operateMaterialCheck('cancel')">取消</a-button>
			<a-button size="small" class="bottom_btn" @click="operateMaterialCheck('all_check')">全选</a-button>
			<a-badge class="bottom_btn" :count="showBottomCount">
				<a-button size="small" @click="handleAddMaterial" type="primary">添加到素材</a-button>
			</a-badge>
		</div>

		<!-- 文字转语音 -->
		<AddDubbing :visible="visibleDubbing" @onCancel="closeDubbing" @successMaterial="successMaterial" />

		<material-position :title="positionData.title" :dataList="positionData.dataList" :visible="positionData.visible"
			:materialType="positionData.type" @submit="handleSelectType" @close="positionData.visible = false" />
	</div>
</template>

<script>
	import {
		defineComponent,
		reactive,
		toRefs,
		computed,
		watch,
		toRaw,
		createVNode,
		ref,
		nextTick,
	} from "vue";
	import {
		FolderAddOutlined,
		LeftOutlined
	} from "@ant-design/icons-vue";
	import NewFolder from "../../../MaterialCenter/modules/NewFolder.vue";
	import UploadFileModal from "../../../MaterialCenter/modules/UploadFileModal.vue";

	import merchantMaterials from "./modules/merchantMaterials.vue";
	import generalMaterials from "./modules/generalMaterials.vue";
	import popularMaterials from "./modules/popularMaterials.vue";
	import popularMusic from "./modules/popularMusic.vue";
	import folderList from "./modules/folderList.vue";
	import materialList from "./modules/materialList.vue";
	import MaterialPosition from "./modules/materialPosition.vue";
	import request from "../../../../../common/utils/request";
	import store from "@/store";
	import AddDubbing from "./modules/AddDubbing.vue";
	import {
		message
	} from "ant-design-vue";
	import {
		useInfiniteScroll
	} from "@vueuse/core";
	export default defineComponent({
		props: {
			currentMaterial: {
				type: Object,
				default: () => {
					return {};
				},
			},
		},
		components: {
			FolderAddOutlined,
			NewFolder,
			merchantMaterials,
			generalMaterials,
			popularMaterials,
			popularMusic,
			folderList,
			materialList,
			LeftOutlined,
			UploadFileModal,
			AddDubbing,
			MaterialPosition,
		},
		name: "EditingCenter",
		setup(props, context) {
			const state = reactive({
				folderLoading: false,
				materialLoading: false,
				folderVisible: false,
				materialVisible: false,
				currentLibrary: {},
				folderData: [],
				materialData: [],
				currentFolder: {},
				showMaterial: false,
				tagList: [],
				mainConHeight: 0,
				showBottomCount: 0,
				checkType: "",
				visibleDubbing: false,
				currentTagId: 0,
				positionData: {
					title: "",
					visible: false,
					dataList: [],
					type: "audio", // image audio video
				},
				selectMaterial: [],
				hasMore: false,
				pageInfo: {
					pageSize: 25,
					page: 1,
					total: 0
				}
			});

			const addFolder = () => {
				state.folderVisible = true;
			};

			const closeFolder = () => {
				state.folderVisible = false;
				let params = {}
				Object.assign(params, state.currentLibrary)
				if(store.getters.clipJSON?.edit_model == 5){
					params.material_type = 'image_text'
				}
				getFolderList(params);
			};

			const chooseFolder = (item) => {
				state.currentFolder = item;
				if (item.folder_type == "text") {
					getTextList({
						merchant_folder_statck_id: item.id
					});
				} else {
					getMediaList({
						isLoad: false,
						merchant_folder_statck_id: item.id,
						folder_type: item.folder_type,
					});
				}
				state.showMaterial = true;
			};

			const getMediaList = (params) => {
				if(!params?.isLoad){
					state.pageInfo.page = 1
					state.materialData = [];
				}
				state.materialLoading = true;
				request.post("/work_ai", "/user/shotstack/media/list", {...params, ...state.pageInfo}).then(res=> {
					state.materialData = [...state.materialData, ...res.result.data];
					state.pageInfo.total = res.result.total;
					if(state.materialData?.length < res.result.total){
						state.hasMore = true
					}
					if(state.materialData?.length == res.result.total){
						state.hasMore = false
					}
					state.materialLoading = false;
				})
			};

			const getTextList = (params) => {
				state.materialLoading = true;
				state.materialData = [];
				request
					.get("/work_ai", "/user/shotstack/text/list", params)
					.then((res) => {
						state.materialData = res.result;
						state.materialLoading = false;
					});
			};

			const addMaterial = () => {
				state.materialVisible = true;
			};

			const closeMaterial = () => {
				state.materialVisible = false;
				if (state.currentFolder.folder_type == "text") {
					getTextList({
						merchant_folder_statck_id: state.currentFolder.id
					});
				} else {
					getMediaList({
						isLoad: false,
						merchant_folder_statck_id: state.currentFolder.id,
						folder_type: state.currentFolder.folder_type,
					});
				}
			};

			const textToAudio = () => {
				state.visibleDubbing = true;
			};

			const closeDubbing = () => {
				state.visibleDubbing = false;
			};

			const chooseMaterial = (arr) => {
				state.selectMaterial = arr;
			};

			const getCurrentLibrary = (obj) => {
				state.currentLibrary = obj;
				let params = {}
				Object.assign(params, obj)
				if(store.getters.clipJSON?.edit_model == 5){
					params.material_type = 'image_text'
				}
				getFolderList(params);
			};

			const backToFolder = () => {
				state.currentFolder = {};
				state.showMaterial = false;
				state.showBottomCount = 0;
				state.checkType = "";
				if (store.getters.clipJSON?.edit_model == 5) {
					state.tagList = [{
						id: 1,
						name: "全部",
						material_type: "",
					},{
						id: 4,
						name: "图片",
						material_type: "image",
					},{
						id: 5,
						name: "文案",
						material_type: "text",
					}]
					return
				}
				state.tagList = [{
					id: 1,
					name: "全部",
					material_type: "",
				},{
					id: 2,
					name: "视频",
					material_type: "video",
				},{
					id: 3,
					name: "音频",
					material_type: "audio",
				},{
					id: 4,
					name: "图片",
					material_type: "image",
				},{
					id: 5,
					name: "文案",
					material_type: "text",
				}];
			};

			const getMaterialTags = (type) => {
				request
					.get("/work_ai", "/user/shotstack/material/tags", {
						scene_type: type
					})
					.then((res) => {
						state.tagList = res.result;
						let params = {};
						params["tag_id"] = state.tagList[1].id;
						if (type == "video") {
							getMaterialVideo(params);
						} else {
							getMaterialMusic(params);
						}
					});
			};

			const getMaterialVideo = (params) => {
				state.materialLoading = true;
				state.materialData = [];
				request
					.get("/work_ai", "/user/shotstack/material/video/list", params)
					.then((res) => {
						state.materialData = res.result;
						state.materialLoading = false;
					});
			};

			const getMaterialMusic = (params) => {
				state.materialLoading = true;
				state.materialData = [];
				request
					.get("/work_ai", "/user/shotstack/material/bgm/list", params)
					.then((res) => {
						state.materialData = res.result;
						state.materialLoading = false;
						state.materialData.map((item) => {
							const findIndex = store.getters.clipJSON.bgm.findIndex(
								(i) => i.id == item.id
							);
							if (findIndex > -1) {
								item.checked = true;
								item.selected = true;
								item.disabled = true;
							} else {
								item.checked = false;
								item.selected = false;
								item.disabled = false;
							}

							return item;
						});
					});
			};

			const getFolderList = (params) => {
				let obj = {};
				obj.merchant_library_id = params.merchant_library_id;
				obj.folder_use_type = 1;
				obj.group_id = params.id;
				if (params.material_type) {
					obj.material_type = params.material_type;
				}
				state.folderLoading = true;
				state.folderData = [];
				request
					.post("/work_ai", "/user/shotstack/folder/list", obj)
					.then((res) => {
						state.folderData = res.result.data;
						state.folderLoading = false;
					});
			};

			const handleTypeChange = (index) => {
				let params = {};
				Object.assign(params, state.currentLibrary);
				params.material_type = state.tagList[index].material_type;
				if(store.getters.clipJSON?.edit_model == 5 && !params.material_type){
					params.material_type = 'image_text'
				}
				getFolderList(params);
			};

			const screenMaterial = (params) => {
				let obj = {};
				obj.tag_id = params.id;
				state.currentTagId = params.id;
				if (params.material_name) {
					obj.material_name = params.material_name;
				}
				if (params.scene_type == "video") {
					getMaterialVideo(obj);
				} else if (params.scene_type == "bgm") {
					getMaterialMusic(obj);
				}
			};

			const expandTab = (flag) => {
				nextTick(() => {
					state.mainConHeight = document.getElementById("mainCon").clientHeight;
				});
			};

			const showBottom = (count) => {
				state.showBottomCount = count;
				state.checkType = "";
			};

			const operateMaterialCheck = (type) => {
				state.checkType = type;

				state.selectMaterial = state.materialData.filter(
					(i) => i.selected !== true
				);
			};

			const handleSelectType = (val) => {
				// bgm audio
				if (val === "bgm" || val === "audio") {
					let flag1 = false;
					let flag2 = false;
					const bgmOrAudioData = JSON.parse(
						JSON.stringify(store.getters.clipJSON[val])
					);
					state.selectMaterial?.map((item) => {
						if (
							item.checked &&
							bgmOrAudioData?.findIndex((i) => i.id == item.id) > -1
						) {
							flag1 = true;
						}

						if (
							item.checked &&
							bgmOrAudioData.findIndex((i) => i.id == item.id) === -1
						) {
							flag2 = true;
							bgmOrAudioData.push(item);
						}
					});
					if (flag1) {
						message.success("部分素材重复添加，已自动剔除！");
					}
					if (!flag1 && flag2) {
						message.success("操作成功！");
					}
					state.selectMaterial.map((i) => (i.checked = false));
					if (val === "bgm") {
						store.dispatch("SetClipJSONBgmData", bgmOrAudioData);
					}
					if (val === "audio") {
						store.dispatch("SetClipJsonAudioData", bgmOrAudioData);
					}
					state.showBottomCount = 0;
				} else {
					// 视频 val是index
					let flag1 = false;
					let flag2 = false;
					
					let data = []
					if(store.getters.clipJSON?.edit_model == 5){
						data = store.getters.clipJSON.resource_data?.[val]?.images;
					} else {
						data = store.getters.clipJSON.resource_data?.[val]?.video;
					}

					state.selectMaterial?.map((item) => {
						if (item.checked && data?.findIndex((i) => i.id == item.id) > -1) {
							flag1 = true;
						}

						if (item.checked && data.findIndex((i) => i.id == item.id) === -1) {
							flag2 = true;
							data.push(item);
						}
					});
					if (flag1) {
						message.success("部分素材重复添加，已自动剔除！");
					}
					if (!flag1 && flag2) {
						message.success("操作成功！");
					}
					state.selectMaterial.map((i) => (i.checked = false));
					state.showBottomCount = 0;
					store.dispatch("UpdateResourceData", {
						index: val,
						data,
					});
				}
			};

			const handleAddMaterial = () => {
				// 热门素材
				if (props.currentMaterial?.id === 3) {
					state.positionData.title = "全部场景";
					state.positionData.visible = true;
					state.positionData.dataList =
						store.getters.clipJSON?.resource_data?.map((item, index) => ({
							value: index,
							label: item.name,
							icon: "",
						}));
				}

				// 项目素材 口播
				if (props.currentMaterial?.id === 1 || props.currentMaterial?.id === 2) {
					if (
						state.currentFolder?.folder_type === "video" ||
						state.currentFolder?.folder_type === "image"
					) {
						state.positionData.title = "全部场景";
						state.positionData.visible = true;
						state.positionData.dataList =
							store.getters.clipJSON?.resource_data?.map((item, index) => ({
								value: index,
								label: item.name,
								icon: "",
							}));
					}

					if (state.currentFolder?.folder_type === "audio") {
						state.positionData.title = "";
						state.positionData.visible = true;
						state.positionData.dataList = [{
								value: "audio",
								label: "口播",
								icon: "icon-koubo"
							},
							{
								value: "bgm",
								label: "音乐",
								icon: "icon-yinle1"
							},
						];
					}
				}

				// 添加素材
				if (props.currentMaterial?.id === 4) {
					state.positionData.visible = false;
					state.showBottomCount = 0;
					store.dispatch("SetClipJSONBgmData", [
						...store.getters.clipJSON.bgm,
						...state.selectMaterial,
					]);
				}
			};

			watch(
				() => props.currentMaterial,
				(val) => {
					state.materialData = [];
					if (val.id == 3) {
						state.showMaterial = true;
						getMaterialTags("video");
					} else if (val.id == 4) {
						state.showMaterial = true;
						getMaterialTags("bgm");
					} else if (val.id == 1) {
						backToFolder();
					} else if (val.id == 2) {
						backToFolder();
					}
					if (val.id == 3 || val.id == 4) {
						nextTick(() => {
							state.mainConHeight =
								document.getElementById("mainCon").clientHeight;
						});
					} else {
						state.mainConHeight = 86;
					}
					state.showBottomCount = 0;
					state.checkType = "";
				}
			);

			const refrashMaterial = (item) => {
				let index = state.materialData.findIndex((v) => v.id == item.id);
				state.materialData.splice(index, 1);
			};

			//保存音频素材后的回调
			const successMaterial = () => {
				getMediaList({
					isLoad: false,
					merchant_folder_statck_id: state.currentFolder.id,
					folder_type: state.currentFolder.folder_type,
				});
			};

			watch(
				() => store.getters.reloadResource,
				(val) => {
					if (
						(props.currentMaterial.id == 1 || props.currentMaterial.id == 2) &&
						state.showMaterial &&
						state.currentFolder.folder_type == "audio"
					) {
						getMediaList({
							isLoad: false,
							merchant_folder_statck_id: state.currentFolder.id
						});
					}
				}
			);
			
			const resultRef = ref(null)
			useInfiniteScroll(
				resultRef,
				() => {
					state.pageInfo.page ++
					state.hasMore = false
					getMediaList({
						isLoad: true,
						merchant_folder_statck_id: state.currentFolder.id
					});
				},
				{ distance: 10, canLoadMore: () => state.hasMore }
			);

			return {
				resultRef,
				addFolder,
				closeFolder,
				chooseFolder,
				addMaterial,
				textToAudio,
				backToFolder,
				closeMaterial,
				screenMaterial,
				getCurrentLibrary,
				getFolderList,
				handleTypeChange,
				expandTab,
				showBottom,
				operateMaterialCheck,
				closeDubbing,
				...toRefs(state),
				successMaterial,
				refrashMaterial,
				handleSelectType,
				handleAddMaterial,
				chooseMaterial,
			};
		},
	});
</script>

<style lang="less" scoped>
	.source_material {
		width: 100%;
		height: 100%;
		background-color: #1e1e20;
		border-left: 1px solid #000;
		position: relative;

		.new_folder {
			padding: 20px;

			.folder_btn {
				color: #ddd;
				background-color: #555;
				font-size: 12px;
			}
		}

		.new_material {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20px;

			.folder_btn {
				color: #ddd;
				background-color: #555;
				font-size: 12px;
			}
		}

		.title_con {
			color: #fff;
			padding: 0 20px;
		}

		.main_con {
			padding: 0 20px;
		}

		.material_bottom {
			width: 100%;
			height: 70px;
			position: absolute;
			left: 0;
			bottom: 0;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-right: 20px;

			.bottom_btn {
				margin-right: 10px;
			}
		}

		.material_con {
			padding: 0 20px;
			max-height: calc(100% - 200px);
			overflow-y: scroll;

			&::-webkit-scrollbar {
				width: 6px;
			}

			&::-webkit-scrollbar-track {
				width: 5px;
				background-color: transparent;
				-webkit-border-radius: 4px;
				-moz-border-radius: 4px;
				border-radius: 4px;
			}

			&::-webkit-scrollbar-thumb {
				background-color: rgba(193, 193, 193, 0.5);
				background-clip: padding-box;
				min-height: 28px;
				-webkit-border-radius: 4px;
				-moz-border-radius: 4px;
				border-radius: 4px;
			}
		}
	}
</style>